package org.lex.dbq.view.metadata;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.lex.dbq.model.jdbc.resultset.AbstractResultSet;
import org.lex.dbq.view.sql.result.TableResultViewer;
import org.lex.jdbc.ResultSetWrapper;
import org.lex.jdbc.util.SQLTypes;

public class TypeDialog extends Dialog {
	private Connection con = null;
	private TableResultViewer viewer = null;

	public TypeDialog(Shell shell, Connection con) {
		super(shell);
		this.con = con;
		this.setShellStyle(SWT.MAX | SWT.MIN | SWT.RESIZE);
	}

	@Override
	protected void configureShell(Shell shell) {
		super.configureShell(shell);
		shell.setText("Schema");
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		GridData d = new GridData(GridData.FILL_BOTH);
		viewer = new TableResultViewer(parent, SWT.NONE);
		viewer.setLayoutData(d);

		if (null != con) {
			try {

				viewer.setResultSet(new AbstractResultSet() {
					@Override
					public ResultSet execute() throws SQLException {
						ResultSet rs = con.getMetaData().getTypeInfo();
						ResultSet wr = new ResultSetWrapper(rs) {
							@Override
							public Object getObject(int columnIndex) throws SQLException {
								if (2 == columnIndex) {
									int type = this.getInt(columnIndex);
									return SQLTypes.getName(type);
								} else {
									return super.getObject(columnIndex);
								}
							}
						};
						return wr;
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return parent;
	}
}
